package com.gt.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gt.common.annotation.Log;
import com.gt.common.config.GtConfig;
import com.gt.common.constant.Constants;
import com.gt.common.core.controller.BaseController;
import com.gt.common.core.domain.AjaxResult;
import com.gt.common.core.page.TableDataInfo;
import com.gt.common.enums.BusinessType;
import com.gt.common.utils.file.FileUtils;
import com.gt.admin.domain.Reg;
import com.gt.admin.service.IRegService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 制度文件controller
 */
@Api(tags = "sc-制度文件")
@RestController
@RequestMapping("/reg")
public class RegController extends BaseController {
    @Autowired
    private IRegService regService;

    /**
     * 查询制度文件列表
     */
    @ApiOperation("查询制度文件列表")
    @GetMapping
    public TableDataInfo list(Reg reg){
        LambdaQueryWrapper<Reg> queryWrapper = new LambdaQueryWrapper<>(reg);
        List<Reg> list = regService.list(queryWrapper);
        return getDataTable(list);
    }

//    @ApiOperation("制度文件上传")
//    @PostMapping("/upload")
//    public AjaxResult upload(@RequestParam("regfile")MultipartFile file)throws Exception{
//        if(!file.isEmpty()){
//            String reg = FileUploadUtils.upload(GtConfig.getUploadPath(), file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
//            return AjaxResult.success(reg);
//        }return error("文件上传异常，请联系管理员");
//    }

    /**
     * 新增制度文件
     */
    @ApiOperation("新增制度文件")
    @Log(title = "制度文件", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult insert(@RequestBody Reg reg){
        reg.setPublisher(getLoginUser().getUsername());
        reg.setPublishDate(new Date());
        return toAjax(regService.save(reg));
    }

    /**
     * 删除制度文件
     */
    @ApiOperation("删除制度文件")
    @Log(title = "制度文件", businessType = BusinessType.DELETE)
    @DeleteMapping("/{regId}")
    public AjaxResult delete(@PathVariable Long regId){
        Reg reg = regService.getById(regId);
        String path = reg.getPath().replace(Constants.RESOURCE_PREFIX, GtConfig.getProfile());
        boolean del = FileUtils.deleteFile(path);
        if (del){
            return toAjax(regService.removeById(regId));
        }else {
            return error("文件删除失败，请联系管理员");
        }
    }
}
